<?php 
// Hook function to create the custom table after switching themes
add_action('switch_theme', 'custom_create_table_after_theme_switch');

function custom_create_table_after_theme_switch() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'message_form_data';

    // Check if the table doesn't already exist
    if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            name varchar(255) NOT NULL,
            phone varchar(15) NOT NULL,
            email varchar(100) NOT NULL,
            details text NOT NULL,
            message_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
}

//创建表格短代码 
//

function custom_contact_form_shortcode() {
    ob_start(); // Start output buffering
    $verification_code = generate_verification_code();

    // Generate the verification code image
$verification_image_url = generate_verification_image($verification_code);
    ?>
    <form action="#" method="post" class="wpcf7-form init" name="Inquiry">
        
        
        <input type="hidden" id="generated-code" value="<script>document.write(verificationCode)</script>">

        <p> <span class="wpcf7-form-control-wrap your-name">
            <input type="text" name="contacts" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" id="your-name" placeholder="Your Name (required)">
            </span> </p>

        <p> <span class="wpcf7-form-control-wrap your-phone">
            <input type="tel" name="mobile" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-tel wpcf7-validates-as-tel" id="your-phone" placeholder="Your Phone">
            </span> </p>
        <p> <span class="wpcf7-form-control-wrap your-email">
            <input type="email" name="email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" id="your-email" placeholder="Your Email (required)">
            </span> </p>
        <p> <span class="wpcf7-form-control-wrap your-message">
            <textarea name="content" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" id="your-message" placeholder="Please fill in the details"></textarea>
            </span> </p>

             <label for="user_verification_code">Enter the Verification Code:</label>
    <img src="<?php echo $verification_image_url; ?>" alt="Verification Code">
    <input type="hidden" name="actual_verification_code" value="<?php echo $verification_code; ?>">
    <input type="text" name="user_verification_code" required>
    <br>
    <br>


        <p class="btn-submit">
            <input type="submit" value="Submit" class="wpcf7-form-control wpcf7-submit" name="button">
        </p>

       
    </form>
    <?php

    return ob_get_clean(); // Return the buffered content
}
add_shortcode('tr_contact_form', 'custom_contact_form_shortcode');


function enqueue_custom_scripts() {
    wp_enqueue_script( 'custom-form-script', get_template_directory_uri() . '/js/plugin.js', array( 'jquery' ), '1.0', true );
   wp_localize_script( 'custom-form-script', 'handle', array(
    'site_url'  => home_url(),
    'ajax_url' => admin_url( 'admin-ajax.php' ),
    'nonce' => wp_create_nonce('wp_rest'),

   ) );
}

add_action( 'wp_enqueue_scripts', 'enqueue_custom_scripts' );



//表格数据提交到后台 数据库 

function handle_message_form_submission( $data ) {
    global $wpdb;


     $actual_verification_code = $data->get_param('actual_verification_code');
    $user_verification_code = $data->get_param('user_verification_code');

    if ($actual_verification_code === $user_verification_code) {
        // Verification code is valid, process the form
        $table_name = $wpdb->prefix . 'message_form_data';
    $title = sanitize_text_field( $data['title'] );
    $contacts = sanitize_text_field( $data['contacts'] );
    $mobile = sanitize_text_field( $data['mobile'] );
    $email = sanitize_email( $data['email'] );
    $content = sanitize_textarea_field( $data['content'] );

    $wpdb->insert(
        $table_name,
        array(
            'id' => $title,
            'name' => $contacts,
            'phone' => $mobile,
            'email' => $email,
            'details' => $content,

        )
    );

    return 'Form data submitted successfully.';
    } else {
        // Verification code is invalid, return an error response
        return '验证码不正确！';
    }

    
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'message-form/v1', '/submit', array(
        'methods' => 'POST',
        'callback' => 'handle_message_form_submission',
        'permission_callback'  => '__return_true'
    ) );
} );


function generate_verification_code($length = 6) {
    $characters = '0123456789';
    $verification_code = '';
    for ($i = 0; $i < $length; $i++) {
        $verification_code .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $verification_code;
}



function generate_verification_image($verification_code) {
    $image = imagecreatetruecolor(200, 75);
    $bg_color = imagecolorallocate($image, 255, 255, 255);
    $text_color = imagecolorallocate($image, 0, 0, 0);
    imagefill($image, 0, 0, $bg_color);

    // Use a font that's available on your system
    $font_size = 30;
    
    $font_path = get_template_directory() . '/css/webfonts/fa-brands-400.ttf';

    imagettftext($image, $font_size, 0, 10, 50, $text_color, $font_path, $verification_code);

    // Get the uploads directory information
    $upload_dir_info = wp_upload_dir();
    $image_path = $upload_dir_info['basedir'] . '/' . uniqid() . '.png'; // Adjust the path

    imagepng($image, $image_path);
    imagedestroy($image);

    $image_url = str_replace($upload_dir_info['basedir'], $upload_dir_info['baseurl'], $image_path);
    return $image_url; // Return the URL of the generated image
}


// Add a submenu page under the "Settings" menu
add_action('admin_menu', 'add_custom_admin_page');

function add_custom_admin_page() {
    add_submenu_page(
        'options-general.php',
        'Message Form Data',
        'Message Form Data',
        'manage_options',
        'custom-message-data',
        'render_custom_admin_page'
    );
}

// Include the WP_List_Table class
require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';

class Custom_Message_Table extends WP_List_Table {
    private $table_name;

    public function __construct() {
        parent::__construct(array(
            'singular' => 'message',
            'plural' => 'messages',
            'ajax' => false
        ));

        global $wpdb;
        $this->table_name = $wpdb->prefix . 'message_form_data';
    }

    public function get_columns() {
        return array(
            'cb' => '<input type="checkbox" />',
            'id' => __('ID'),
            'name' => __('Name'),
            'phone' => __('Phone'),
            'email' => __('Email'),
            'details' => __('Details'),
            'message_time' => __('Message Time')
        );
    }

    public function prepare_items() {
        $per_page = 20;

        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();

        $this->_column_headers = array($columns, $hidden, $sortable);

        $current_page = $this->get_pagenum();
        $total_items = $this->get_total_items();

        $this->set_pagination_args(array(
            'total_items' => $total_items,
            'per_page'    => $per_page
        ));

        $this->items = $this->get_items($per_page, $current_page);
    }

    private function get_total_items() {
        global $wpdb;
        $query = "SELECT COUNT(*) FROM $this->table_name";
        return $wpdb->get_var($query);
    }

    private function get_items($per_page, $current_page) {
        global $wpdb;
        $orderby = isset($_REQUEST['orderby']) ? $_REQUEST['orderby'] : 'message_time';
        $order = isset($_REQUEST['order']) ? $_REQUEST['order'] : 'desc';
        $search = isset($_REQUEST['s']) ? sanitize_text_field($_REQUEST['s']) : '';

        $offset = ($current_page - 1) * $per_page;

        $query = "SELECT * FROM $this->table_name";

        if (!empty($search)) {
            $query .= " WHERE name LIKE '%$search%' OR phone LIKE '%$search%' OR email LIKE '%$search%'";
        }

        $query .= " ORDER BY $orderby $order LIMIT $per_page OFFSET $offset";

        return $wpdb->get_results($query, ARRAY_A);
    }

    public function column_default($item, $column_name) {
        return $item[$column_name];
    }
    
     public function column_cb($item) {
        return sprintf(
            '<input type="checkbox" name="bulk-delete[]" value="%s" />',
            $item['id']
        );
    }

     public function column_number($item) {
        return $item['number'];
    }

    public function get_sortable_columns() {
        $sortable_columns = array(
            'name' => array('name', false),
            'phone' => array('phone', false),
            'email' => array('email', false),
            'message_time' => array('message_time', false)
        );
        return $sortable_columns;
    }

    public function search_box($text, $input_id) {
        $search = isset($_REQUEST['s']) ? sanitize_text_field($_REQUEST['s']) : '';
        ?>
        <p class="search-box">
            <label class="screen-reader-text" for="<?php echo $input_id ?>"><?php echo $text ?>:</label>
            <input type="search" id="<?php echo $input_id ?>" name="s" value="<?php echo $search ?>" />
            <?php submit_button($text, 'button', false, false, array('id' => 'search-submit')); ?>
        </p>
        <?php
    }
}



function render_custom_admin_page() {
    // Display HTML content here, and create an instance of your custom WP_List_Table
    echo '<div class="wrap">';
    echo '<h1>Message Form Data</h1>';

    // Enqueue necessary styles and scripts for the table
    $table_styles = array('wp-lists');
    
    // Create an instance of your custom WP_List_Table
    $table = new Custom_Message_Table();
    $table->prepare_items();
    echo '<form method="post">';
    $table->search_box('Search', 'message-search');
    echo '</form>';
    $table->display();

    echo '</div>';
}

// Enqueue styles and scripts
function custom_list_table_scripts() {
    wp_enqueue_style('wp-list-table');
    wp_enqueue_script('wp-lists');
    
}
add_action('admin_enqueue_scripts', 'custom_list_table_scripts');





